package com.msb.crm.aspect;


import com.msb.crm.annotation.RequiredPermission;
import com.msb.crm.exceptions.AuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

@Component
@Aspect
public class Permission {

    @Autowired
    private HttpSession httpSession;


    /**
     * 环绕通知  用切面来拦截指定注解标注的方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around(value = "@annotation(com.msb.crm.annotation.RequiredPermission)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
      List<String> permissions = (List<String>) httpSession.getAttribute("permissions");
      if (null == permissions || permissions.size()<1){
          throw new AuthException();
      }
        Object result = null;
        //得到对应的目标
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        //得到方法上的注解
        RequiredPermission requiredPermission = methodSignature.getMethod().getDeclaredAnnotation(RequiredPermission.class);
        //判断注解上对应的状态码
        if (!(permissions.contains(requiredPermission.code()))){
            //如果权限中不包含当前方法注解的状态码，就抛出异常
            throw new AuthException();
        }
        result = pjp.proceed();
        return result;
    }
}
